<?php
/**
 * 语言常量
 *
 * @author Zeon <scplay@gmail.com>
 * @date 2018/6/4 9:18
 * @copyright PanxSoft Inc.
 */

namespace App\Services\Locale;
use App\Models\Language as LanguageModel;

class Language
{
    /**
     * @param $lang
     */
    public static function setAppLocale(string $lang): void
    {
        app()->setLocale(self::normalizeLocale($lang));
    }

    public static function isCN($locale = null): bool
    {
        $locale = $locale ?: app()->getLocale();

        return str_contains(strtolower($locale), ['cn', 'zh']);
    }

    /**
     * @example
     *      'zh-CN,zh;q=0.9,en;q=0.8,ja;q=0.7,fr;q=0.6,zh-TW;q=0.5'
     *   => 'zh-CN'
     *
     * @test
     *
     * @param string|null $header_lang
     *
     * @return array|string
     */
    public static function normalizeHeaderLanguage(string $header_lang = null): ?string
    {
        if (! $header_lang) return null;

        $locale_weight = head(explode(',', $header_lang));

        $locale_lang = head(explode(';', $locale_weight));

        return $locale_lang;
    }

    /**
     * 根据语言返回顿号
     *
     * @return string
     */
    public static function localeComma()
    {
        $comma_cn = '、';
        $comma_en = ',';

        return app()->getLocale() === LanguageModel::getStoreSettingLanguageCode()
            ? $comma_cn
            : $comma_en;
    }

    /**
     * Laravel 会找 resources/lang 下面对应文件夹名称对语言文件
     * 对于 zh_CN 等形式，会导致 app()->setLocale() 找不到对应的目录
     * 而变成 fallback 语言，setLocale 前必须把 zh_CN 转成 zh-cn 的形式
     *
     * @param string $language_code
     *
     * @return string
     */
    public static function normalizeLocale(string $language_code): string
    {
        return strtolower(str_slug($language_code));
    }
}